package com.hongdee.market.bc.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.market.bc.dao.ITBcCustomLevelDao;
import com.hongdee.market.bc.entity.TBcCustomeLevelConf;
import com.hongdee.market.bc.service.ITBcCustomLevelConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangguokai
 */
@Service
public class TBcCustomLevelConfServiceImpl implements ITBcCustomLevelConfService {
    @Autowired
    private ITBcCustomLevelDao itBcCustomLevelDao;
    private String tabName = "T_BC_CUSTOME_LEVEL_CONF";
    private String tapName = "T_BC_CUSTOME_LEVEL";
    private String taIName = "T_BC_CUSTOME_ITEM";
    @Autowired
    private IHibernateDao iHibernateDao;

    /**
     * 启用停用
     */
    @Override
    public void update(String id, String status) throws Exception {
        String hql = "update TBcCustomeLevelConf set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.itBcCustomLevelDao.update(hql, params);
    }

    /**
     * 新增、更新
     *
     * @param tBcCustomeLevelConf
     * @return
     * @throws Exception
     */
    @Override
    public TBcCustomeLevelConf saveOrUpdate(TBcCustomeLevelConf tBcCustomeLevelConf) throws Exception {

        /**
         *
         *   1. 每个等级只允许有一条记录
         *   2. 每个记录的值不允许相同
         *   3. 分值计算时按升序排序
         * **/

        if (StringUtils.isEmpty(tBcCustomeLevelConf.getId())) {
            tBcCustomeLevelConf.setId(null);
        }
        tBcCustomeLevelConf.setStatus("1");
        // 判断是否存在相同的等级编码
        if (null != tBcCustomeLevelConf.getId()) {
            String sql = "select * from T_BC_CUSTOME_LEVEL_CONF where level_code = ? and id != ? ";
            List ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getLevelCode(), tBcCustomeLevelConf.getId());
            if (ls != null && ls.size() > 0) {
                throw new Exception("已存在相同的等级值，请修改后保存！");
            }

            if ("1".equals(tBcCustomeLevelConf.getScoreType())) {
                sql = "select * from T_BC_CUSTOME_LEVEL_CONF where start = ? and score_type = '1' and id != ? ";
                ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getStart(), tBcCustomeLevelConf.getId());
                if (ls != null && ls.size() > 0) {
                    throw new Exception("得分方式下已存在相同的分值，请修改后保存！");
                }
            } else if ("2".equals(tBcCustomeLevelConf.getScoreType())) {

                sql = "select * from T_BC_CUSTOME_LEVEL_CONF where score_item = ? and score_type = '2' and id != ? ";
                ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getScoreItem(), tBcCustomeLevelConf.getId());
                if (ls != null && ls.size() > 0) {
                    throw new Exception("项目评分方式下已存在相同的项目，请修改后保存！");
                }
            }
        } else {
            String sql = "select * from T_BC_CUSTOME_LEVEL_CONF where level_code = ?  ";
            List ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getLevelCode());
            if (ls != null && ls.size() > 0) {
                throw new Exception("已存在相同的等级值，请修改后保存！");
            }
            if ("1".equals(tBcCustomeLevelConf.getScoreType())) {
                sql = "select * from T_BC_CUSTOME_LEVEL_CONF where start = ? and score_type = '1' ";
                ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getStart());
                if (ls != null && ls.size() > 0) {
                    throw new Exception("得分评分方式下已存在相同的分值，请修改后保存！");
                }
            } else if ("2".equals(tBcCustomeLevelConf.getScoreType())) {

                sql = "select * from T_BC_CUSTOME_LEVEL_CONF where score_item = ? and score_type = '2' ";
                ls = this.itBcCustomLevelDao.list(sql, tBcCustomeLevelConf.getScoreItem());
                if (ls != null && ls.size() > 0) {
                    throw new Exception("项目评分方式下已存在相同的项目，请修改后保存！");
                }
            }
        }


        this.itBcCustomLevelDao.saveOrUpdate(tBcCustomeLevelConf);

        return tBcCustomeLevelConf;
    }

    private boolean isCode(String scoreItem, int type, String id) throws Exception {
        String sql = "select * from " + tabName + " where  id= ?  ";
        List param = new ArrayList();
        param.add(id);
        //项目编码不可以重复
        if (1 == type) {
            sql += " and  item_code != ? ";
            param.add(scoreItem);
        }
        Map map = this.itBcCustomLevelDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }


    /**
     * 根据条件查询
     **/
    @Override
    public Map info(String id) throws Exception {
        String sql = "select * from " + tabName + " where id = ? ";
        return this.itBcCustomLevelDao.info(sql, id);
    }

    /**
     * 分页
     **/
    @Override
    //把数据展示到页面（只要是这里面有的字段，都会在页面上显示出来）
    public Map newPage(String companyId, String start, String limit, String levelCode) throws Exception {


        String sql = "SELECT a.id,a.level_code,a.start,a.stop,a.score_item, a.score_type, a.score_item," +
                " a.count_type, a.company_id, a.disp_order, a.status, b.level_name, b.level_code AS lc," +
                " c.item_code ,c.item_name FROM t_bc_custome_level_conf a LEFT JOIN t_bc_custome_level b" +
                " ON (a.level_code = b.level_code) LEFT JOIN t_bc_custome_item c ON (a.score_item = c.item_code) where a.company_id = ?";

        List<Object> params = new ArrayList();
        params.add(companyId);
        if (!StringUtils.isEmpty(levelCode)) {
            sql += "and (b.level_name like ? or b.level_code like ?)";
            params.add("%" + levelCode + "%");
            params.add("%" + levelCode + "%");
        }
        return this.itBcCustomLevelDao.page(sql, params.toArray(), start, limit);
    }

    /***
     *  获取目标值
     * @param comId 公司 ID
     * @return 结果数组 [1,2,3,4,5,6]
     * @throws Exception
     */
    @Override
    public List target(String comId) throws Exception {

        StringBuffer sql = new StringBuffer("select level_code, stop from t_bc_custome_level_conf where company_id = ? order by level_code ");
        List params = new ArrayList();
        params.add(comId);
        List<Map<String, Object>> ls = this.itBcCustomLevelDao.list(sql.toString(), params.toArray());
        Map<String, Object> lineTempMap = new HashMap(6);

        for (Map temp : ls) {
            lineTempMap.put(temp.get("levelCode").toString(), temp.get("stop"));
        }

        // 拼接 Line
        List resultList = new ArrayList(6);
        if (lineTempMap.containsKey("A")) {
            resultList.add(lineTempMap.get("A"));
        } else {
            resultList.add(0);
        }
        if (lineTempMap.containsKey("B")) {
            resultList.add(lineTempMap.get("B"));
        } else {
            resultList.add(0);
        }
        if (lineTempMap.containsKey("C")) {
            resultList.add(lineTempMap.get("C"));
        } else {
            resultList.add(0);
        }
        if (lineTempMap.containsKey("D")) {
            resultList.add(lineTempMap.get("D"));
        } else {
            resultList.add(0);
        }
        if (lineTempMap.containsKey("E")) {
            resultList.add(lineTempMap.get("E"));
        } else {
            resultList.add(0);
        }
        if (lineTempMap.containsKey("无")) {
            resultList.add(lineTempMap.get("无"));
        } else {
            resultList.add(0);
        }
        return resultList;
    }

    /**
     * 根据CODE 查询等级详情
     *
     * @param code
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public Map code(String code, String companyId) throws Exception {
        String sql = " select * from T_BC_CUSTOME_LEVEL_CONF where level_code = ? and company_id = ? ";
        List params = new ArrayList();
        params.add(code);
        params.add(companyId);
        return this.itBcCustomLevelDao.info(sql, params.toArray());
    }

}